/**
 * ThumbnailUpload.java
 * Wraps an uploaded thumbnail image file in a thumbnail data access object.
 */
package com.example.myproject;


public class ThumbnailUpload {
	
	public ThumbnailUpload(){}
	
	/**
	 * Uploads a thumbnail image file to the blobstore.
	 * @param src The source image file to be uploaded.
	 * @param master 
	 * @return true if successfully uploaded, false if not.
	 */
	public boolean upload(ThumbnailUploadDTO dto)
	{
		
		try {
			
			ThumbnailUploadDAO dao = new ThumbnailUploadDAO();
			ThumbnailUploadDTO savedto = new ThumbnailUploadDTO();
			
			savedto = dao.findByParentId(dto.getParentId());
			
			if(savedto != null)
			{
				dao.deleteByParentId(dto.getParentId());
			}
			
			savedto = dao.save(dto);

			System.out.println("savedto====="+savedto);
			
			if (dto.getType().equals("audio")) 
			{
				AudioUploadDAO picture = new AudioUploadDAO();
				AudioUploadDTO pictureDTO = new AudioUploadDTO();
				
				pictureDTO = picture.findById(dto.getParentId());
				pictureDTO.setThumbnailId(savedto.getId());
				picture.delete(pictureDTO.getId());
				picture.save(pictureDTO);
				
				System.out.println("pictureDTO====="+pictureDTO);
			}
			/* video file upload */
			else if (dto.getType().equals("video")) 
			{
				VideoUploadDAO video = new VideoUploadDAO();
				VideoUploadDTO videoDTO = new VideoUploadDTO();
				
				videoDTO = video.findById(dto.getParentId());
				videoDTO.setThumbnailId(savedto.getId());
				video.delete(videoDTO.getId());
				video.save(videoDTO);

			}
			/* image file upload */
			else if (dto.getType().equals("image")) 
			{
				PictureUploadDAO picture = new PictureUploadDAO();
				PictureUploadDTO pictureDTO = new PictureUploadDTO();
				
				pictureDTO = picture.findById(dto.getParentId());
				pictureDTO.setThumbnailId(savedto.getId());
				picture.delete(pictureDTO.getId());
				picture.save(pictureDTO);

			}
			/* book file upload */
			else if (dto.getType().equals("book") )
			{
				BookUploadDAO book = new BookUploadDAO();
				BookUploadDTO bookDTO = new BookUploadDTO();
				
				bookDTO = book.findById(dto.getParentId());
				bookDTO.setThumbnailId(savedto.getId());
				book.delete(bookDTO.getId());
				book.save(bookDTO);

			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
		return true;
		
	}
	
}
